<template>
  <view class="chat-container">
    <!-- 界面结构保持不变 -->
    <uni-nav-bar
      backgroundColor="transparent"
      color="#000000"
      left-icon="back"
      :border="false"
      :statusBar="true"
      fixed
      title="AI对话"
      @clickLeft="$goBack"
    ></uni-nav-bar>
    <view class="chat-messages" ref="messagesContainer">
      <view class="ai-intro-section">
        <view class="ai-top">
          <view class="ai-img"></view>
          <view class="ai-greeting">Hi, 我是智客小助</view>
        </view>
        <view class="ai-description">
          我是您的导购助手,欢迎向我提出您的采购需求,我会根据您给出的商品需求、用途、所在地、价格等信息提供个性化推荐。
        </view>
      </view>

      <view class="suggested-questions">
        <view class="questions-header">
          <view class="title"></view>
          <button
            class="refresh-btn"
            @click="refreshDefaultQuestions"
            :disabled="isLoadingQuestions"
          >
            <svg
			  class="svg"
              viewBox="0 0 24 24"
              fill="none"
              :class="{ rotating: isLoadingQuestions }"
            >
              <path
                d="M1 4V10H7M23 20V14H17"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
              />
              <path
                d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10M23 14L18.36 18.36A9 9 0 0 1 3.51 15"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
              />
            </svg>
            {{ isLoadingQuestions ? "加载中..." : "换一批" }}
          </button>
        </view>
        <view class="question-list">
          <!-- 加载状态 -->
          <view
            v-if="isLoadingQuestions && defaultQuestions.length === 0"
            class="loading-questions"
          >
            <view class="question-skeleton" v-for="i in 3" :key="i">
              <view class="skeleton-text"></view>
              <view class="skeleton-icon"></view>
            </view>
          </view>
          <!-- 问题列表 -->
          <view v-else>
            <view
              v-for="question in defaultQuestions"
              :key="question.questionsId"
              class="question-item"
              @click="
                sendMessage(question.questionContent, question.questionsId)
              "
            >
              <view>{{ question.questionContent }}</view>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                <path
                  d="M9 18L15 12L9 6"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                />
              </svg>
            </view>
            <!-- 当没有问题时的占位 -->
            <view
              v-if="defaultQuestions.length === 0 && !isLoadingQuestions"
              class="no-questions"
            >
              <view>暂无推荐问题</view>
            </view>
          </view>
        </view>
      </view>

      <view v-for="message in messages" :key="message.id" class="message-group">
        <view v-if="message.type === 'user'" class="user-message">
          <view class="message-bubble user-bubble">
            {{ message.content }}
          </view>
        </view>

        <view v-else class="bot-message">
          <view class="message-bubble bot-bubble">
            <view
              v-html="parseMarkdown(message.content)"
              class="markdown-content"
            ></view>
            <view v-if="message.products" class="product-recommendations">
              <view class="product-carousel">
                <!--              <button-->
                <!--                class="carousel-btn prev-btn"-->
                <!--                @click="scrollProducts('prev')"-->
                <!--                v-if="canScrollLeft"-->
                <!--              >-->
                <!--                <svg width="20" height="20" viewBox="0 0 24 24" fill="none">-->
                <!--                  <path-->
                <!--                    d="M15 18L9 12L15 6"-->
                <!--                    stroke="currentColor"-->
                <!--                    stroke-width="2"-->
                <!--                    stroke-linecap="round"-->
                <!--                    stroke-linejoin="round"-->
                <!--                  />-->
                <!--                </svg>-->
                <!--              </button>-->

                <view class="product-grid" ref="productGrid">
                  <view
                      v-for="product in message.products"
                      :key="product.id"
                      class="product-card"
                  >
                    <view class="product-image">
                      <image
                          :src="formatProductImage(product.image)"
                          :alt="product.name"
                          class="product-img"
                      />
                      <!--                    <view class="product-badge hot" v-if="product.isHot"-->
                      <!--                      >热销商品</view-->
                      <!--                    >-->
                      <!--                    <view-->
                      <!--                      class="product-badge recommended"-->
                      <!--                      v-if="product.isRecommended"-->
                      <!--                      >推荐商品</view-->
                      <!--                    >-->
                      <view
                          class="product-badge discount"
                          v-if="product.discountText"
                      >
                        {{ product.discountText }}
                      </view>
                    </view>
                    <view class="product-info">
                      <view class="product-name">{{ product.productName }}</view>
                      <view class="product-price">
                        <view class="sale-price">¥{{ product.price }}</view>
                        <!--                      <view class="original-price" v-if="product.originalPrice"-->
                        <!--                        >¥{{ product.originalPrice }}</view-->
                        <!--                      >-->
                        <!--                      <view class="price-unit" v-if="product.unit"-->
                        <!--                        >/{{ product.unit }}</view-->
                        <!--                      >-->
                      </view>
                      <!--                    <view class="shop-info" v-if="product.shopName">-->
                      <!--                      <view class="shop-name">{{ product.shopName }}</view>-->
                      <!--                    </view>-->
                      <button
                          class="contact-btn"
                          @click="jumpToProductDetail(product)"
                      >
                        点击查看
                      </button>
                    </view>
                  </view>
                </view>

                <!--              <button-->
                <!--                class="carousel-btn next-btn"-->
                <!--                @click="scrollProducts('next')"-->
                <!--                v-if="canScrollRight"-->
                <!--              >-->
                <!--                <svg width="20" height="20" viewBox="0 0 24 24" fill="none">-->
                <!--                  <path-->
                <!--                    d="M9 18L15 12L9 6"-->
                <!--                    stroke="currentColor"-->
                <!--                    stroke-width="2"-->
                <!--                    stroke-linecap="round"-->
                <!--                    stroke-linejoin="round"-->
                <!--                  />-->
                <!--                </svg>-->
                <!--              </button>-->
              </view>
            </view>
          </view>



          <view v-if="message.followUpQuestions" class="follow-up-questions">
            <view
              v-for="(question, idx) in message.followUpQuestions"
              :key="idx"
              class="follow-up-item"
              @click="sendMessage(question)"
            >
              {{ question }}
            </view>
          </view>

          <view v-if="message.showRegenerate" class="regenerate-section">
            <button class="regenerate-btn" @click="regenerateResponse(message)">
              <svg class="svg" width="16" height="16" viewBox="0 0 24 24" fill="none">
                <path
                  d="M1 4V10H7M23 20V14H17"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                />
                <path
                  d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10M23 14L18.36 18.36A9 9 0 0 1 3.51 15"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                />
              </svg>
              重新生成
            </button>
          </view>
        </view>
      </view>
    </view>

    <view class="chat-input">
      <view class="input-container">
        <input
          v-model="inputMessage"
          @keyup.enter="() => sendUserMessage()"
          placeholder="告诉我你想挑选什么..."
          class="message-input"
        />
        <button
          @click="() => sendUserMessage()"
          class="send-btn"
          :disabled="!isInputValid"
        >
          发送
        </button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, nextTick, computed, inject } from "vue";
import { request } from "@/utils/request.js";
import { DOMAIN_PREFIX } from "../../config/api.js";
import axios from "axios";

const $goBack = inject("$goBack");
// -------------------------- 类型定义 --------------------------
interface Message {
  id: number;
  type: "user" | "bot";
  content: string;
  showActions?: boolean;
  products?: Product[];
  followUpQuestions?: string[];
  showRegenerate?: boolean;
}

interface Product {
  productId: number;
  productName: string;
  price: number;
  originalPrice?: number;
  unit?: string;
  image: string;
  shopName?: string;
  shopId: number;
  shopLogo?: string;
  skuId: number;
  discountText?: string;
  productBrief?: string;
  isHot?: boolean;
  isRecommended?: boolean;
  hasVideo?: boolean;
  users?: any;
  activityType?: number;
  number?: number;
  total?: any;
  detailUrl?: string;
}

interface DefaultQuestion {
  questionsId: number;
  questionContent: string;
}

// -------------------------- 后端API配置 --------------------------
// 推荐商品API（含"推荐"关键词时用）
const API_RECOMMEND = {
  baseUrl: DOMAIN_PREFIX,
  // baseUrl: 'http://127.0.0.1:9007',
  endpoint: "/ai-prod/send",
  timeout: 15000,
  imageDomain: "",
};

// 直接提问API（不含"推荐"关键词时用）
const API_DIRECT = {
  baseUrl: DOMAIN_PREFIX,
  // baseUrl: 'http://127.0.0.1:9007',
  endpoint: "/ai-prod/direct",
  timeout: 15000,
  imageDomain: "",
};

// 重新生成API
const API_REGENERATE = {
  baseUrl: DOMAIN_PREFIX,
  // baseUrl: 'http://127.0.0.1:9007',
  endpoint: "/ai-prod/regenerate",
  timeout: 15000,
  imageDomain: "",
};

// 获取默认问题API
const API_DEFAULT_QUESTIONS = {
  baseUrl: DOMAIN_PREFIX, // http://127.0.0.1:9007
  // baseUrl: 'http://127.0.0.1:9007',
  endpoint: "/ai-prod/default-question",
  timeout: 10000,
};

// 流式响应
const API_STREAM = {
  baseUrl: DOMAIN_PREFIX,
  // baseUrl: 'http://127.0.0.1:9007',
  endpoint: "/ai-prod/stream",
  timeout: 15000,
  imageDomain: "",
};

// 获取默认问题答案API
const API_DEFAULT_QUESTION_ANSWER = {
  baseUrl: DOMAIN_PREFIX,
  // baseUrl: 'http://127.0.0.1:9007',
  endpoint: "/ai-prod/default-question-answer",
  timeout: 15000,
};

// 根据用户输入选择对应的API配置
const getApiConfigByInput = (userInput: string) => {
  // 判断输入是否包含"推荐"（不区分大小写）
  const hasRecommendKeyword = /推荐/.test(userInput.trim());
  return hasRecommendKeyword ? API_RECOMMEND : API_DIRECT;
};

// 处理输入内容，截取"推荐"后面的文字
const processInputForApi = (userInput: string) => {
  const trimmedInput = userInput.trim();
  const recommendIndex = trimmedInput.indexOf("推荐");

  // 如果包含"推荐"且后面有内容，则截取后面的部分
  if (recommendIndex !== -1 && recommendIndex < trimmedInput.length - 2) {
    const processed = trimmedInput.substring(recommendIndex + 2).trim();
    // 如果截取后为空，返回原始输入
    return processed || trimmedInput;
  }

  // 不包含"推荐"或"推荐"在末尾，返回原始输入
  return trimmedInput;
};

// -------------------------- 状态管理 --------------------------
const inputMessage = ref("");
const messagesContainer = ref<HTMLElement>();
const productGrid = ref<HTMLElement>();
const messages = ref<Message[]>([]);
const canScrollLeft = ref(false);
const canScrollRight = ref(true);
const defaultQuestions = ref<DefaultQuestion[]>([]);
const isLoadingQuestions = ref(false);

// 输入框验证（非空且去除空格后长度>0）
const isInputValid = computed(() => {
  return inputMessage.value.trim().length > 0;
});

// -------------------------- Markdown解析 --------------------------
const parseMarkdown = (text: string): string => {
  if (!text) return "";
  let html = text;

  // 1. 橙色背景介绍块
  html = html.replace(
    /```intro\s*([\s\S]*?)```/g,
    '<div class="intro-block">$1</div>'
  );

  // 2. 代码块
  html = html.replace(
    /```([\s\S]*?)```/g,
    '<pre class="code-block"><code>$1</code></pre>'
  );

  // 3. 行内代码
  html = html.replace(/`([^`]+)`/g, '<code class="inline-code">$1</code>');

  // 4. 标题（###/##/#）
  html = html.replace(
    /### (.*?)(?=\n|$)/g,
    '<h3 class="md-heading h3">$1</h3>'
  );
  html = html.replace(/## (.*?)(?=\n|$)/g, '<h2 class="md-heading h2">$1</h2>');
  html = html.replace(/# (.*?)(?=\n|$)/g, '<h1 class="md-heading h1">$1</h1>');

  // 5. 粗体/斜体
  html = html.replace(/\*\*(.*?)\*\*/g, '<strong class="md-bold">$1</strong>');
  html = html.replace(/\*(.*?)\*/g, '<em class="md-italic">$1</em>');

  // 6. 无序列表
  html = html.replace(/\n- (.*?)(?=\n|$)/g, '<li class="md-list-item">$1</li>');
  html = html.replace(
    /(<li class="md-list-item">.*?<\/li>)/g,
    '<ul class="md-list">$1</ul>'
  );

  // 7. 图片（适配接口返回的![alt](src)格式）
  html = html.replace(/!\[(.*?)\]\((.*?)\)/g, (match, alt, src) => {
    const formattedSrc = formatProductImage(src);
    return `<img src="${formattedSrc}" alt="${alt}" class="md-image" />`;
  });

  // 8. 换行处理
  html = html.replace(/\n/g, "<br>");

  return html;
};

// -------------------------- 商品图片格式处理 --------------------------
const formatProductImage = (imageUrl: string): string => {
  if (!imageUrl) return "/api/placeholder/150/150"; // 占位图

  // 获取当前使用的API配置的图片域名
  const currentConfig = getApiConfigByInput(inputMessage.value);

  // 若配置了图片域名且图片URL是相对路径，则拼接域名
  if (currentConfig.imageDomain && imageUrl.indexOf("http") !== 0) {
    return `${currentConfig.imageDomain}${
      imageUrl.indexOf("/") === 0 ? "" : "/"
    }${imageUrl}`;
  }

  return imageUrl;
};

// -------------------------- 页面导航相关 --------------------------

// -------------------------- 发送消息相关 --------------------------
// 调用默认问题答案接口
const fetchDefaultQuestionAnswer = async (
  questionId: number
): Promise<string> => {
  try {
    const response = await request(
      `${API_DEFAULT_QUESTION_ANSWER.baseUrl}${API_DEFAULT_QUESTION_ANSWER.endpoint}`,
      questionId, // 直接传递ID作为请求体
      "POST"
    );
    const apiData = response;
    if (apiData.code === "200" && apiData.data && apiData.data.answer) {
      // 将 \n 转换为换行符
      return apiData.data.answer.replace(/\\n/g, "\n");
    } else {
      console.warn(
        "获取默认问题答案失败:",
        apiData.message || "接口返回数据格式错误"
      );
      return "抱歉，获取答案失败，请稍后再试。";
    }
  } catch (error) {
    console.error("调用默认问题答案接口失败:", error);
    return "抱歉，服务暂时不可用，请稍后再试。";
  }
};

// 发送预设问题
const sendMessage = (content: string, questionId?: number) => {
  inputMessage.value = content;
  sendUserMessage(questionId);
};

// 发送用户消息主逻辑
const sendUserMessage = async (questionId?: number) => {
  if (!isInputValid.value) return;

  // 添加用户消息到列表（显示原始输入）
  const userMessage: Message = {
    id: Date.now(),
    type: "user",
    content: inputMessage.value,
  };
  messages.value.push(userMessage);
  const currentInput = inputMessage.value;
  inputMessage.value = "";
  scrollToBottom();

  // 显示加载状态
  const loadingMessage: Message = {
    id: Date.now() + 1,
    type: "bot",
    content: "正在思考中...",
    showActions: false,
  };
  messages.value.push(loadingMessage);
  scrollToBottom();

  try {
    let botResponse: Message;

    // 如果是默认问题（有questionId），调用默认问题答案接口
    if (questionId) {
      const answer = await fetchDefaultQuestionAnswer(questionId);
      botResponse = {
        id: Date.now() + 1,
        type: "bot",
        content: answer,
        showActions: true,
        showRegenerate: false, // 默认问题答案不支持重新生成
      };
    } else {
      // 否则调用原有的AI对话接口
      botResponse = await generateBotResponse(currentInput);
    }

    // 移除加载消息，添加实际回复
    messages.value.pop();
    messages.value.push(botResponse);
  } catch (error) {
    messages.value.pop();
    messages.value.push({
      id: Date.now() + 1,
      type: "bot",
      content: "抱歉，服务暂时不可用，请稍后再试。",
      showActions: true,
      showRegenerate: true,
    });
  }

  scrollToBottom();
};

// 调用后端接口获取回复
const fetchApiResponse = async (userInput: string) => {
  // 根据用户输入选择对应的API配置
  const apiConfig = getApiConfigByInput(userInput);
  const requestUrl = `${apiConfig.baseUrl}${apiConfig.endpoint}`;

  // 处理输入内容，截取"推荐"后面的文字作为参数
  const processedInput = processInputForApi(userInput);

  try {
    // // 向目标接口发送请求（使用处理后的输入作为参数）
    const response = await request(
      requestUrl,
      {
        userQuery: processedInput, // 传递处理后的参数
      },
      "POST"
    );

    // 解析接口响应
    const apiData = response;
    if (apiData.code === "200" && apiData.data) {
      const { answer, products, followUps, showRegenerate } = apiData.data;

      // 格式化商品数据
      const formattedProducts: Product[] = (products || []).map(
        (item: any) => ({
          productId: item.productId || item.id || Date.now() + Math.random(), // 确保ID唯一
          productName: item.productName || "未命名商品",
          price: item.price || 0,
          originalPrice: item.originalPrice || undefined,
          unit: item.unit || "件",
          image: item.image || "",
          shopName: item.shopName || undefined,
          shopId: item.shopId,
          shopLogo: item.shopLogo || undefined,
          skuId: item.skuId,
          discountText: item.discountText || undefined,
          productBrief: item.productBrief || undefined,
          isHot: item.isHot || false,
          isRecommended: item.isRecommended || false,
          hasVideo: item.hasVideo || false,
          users: item.users,
          activityType: item.activityType || 0,
          number: item.number || 0,
          total: item.total,
          detailUrl: item.detailUrl || undefined,
        })
      );

      return {
        aiAnswer: answer || "已为您找到相关商品，请看推荐~",
        products: formattedProducts,
        followUpQuestions: followUps || [],
        showRegenerate: showRegenerate !== undefined ? showRegenerate : true,
        hasProducts: formattedProducts.length > 0,
      };
    } else {
      // 接口返回成功但无数据
      return {
        aiAnswer: "未找到相关商品信息，您可以补充更多需求~",
        products: [],
        followUpQuestions: ["您可以告诉我更多需求吗？", "需要调整搜索条件吗？"],
        showRegenerate: true,
        hasProducts: false,
      };
    }
  } catch (error) {
    console.error(`调用${apiConfig.endpoint}接口失败:`, error);
    return {
      aiAnswer: "抱歉，服务暂时不可用，请稍后再试~",
      products: [],
      followUpQuestions: [],
      showRegenerate: true,
      hasProducts: false,
    };
  }
};

// 生成Bot回复
const generateBotResponse = async (userInput: string): Promise<Message> => {
  try {
    // 调用API获取接口返回数据
    const searchResult = await fetchApiResponse(userInput);

    // 组装Bot消息
    return {
      id: Date.now() + 1,
      type: "bot",
      content: searchResult.aiAnswer,
      showActions: true,
      products: searchResult.hasProducts ? searchResult.products : undefined,
      followUpQuestions: searchResult.followUpQuestions,
      showRegenerate: searchResult.showRegenerate,
    };
  } catch (error) {
    console.error("生成Bot回复失败:", error);
    return {
      id: Date.now() + 1,
      type: "bot",
      content: "抱歉，生成回复失败，请稍后再试~",
      showActions: true,
      showRegenerate: true,
    };
  }
};

// 重新生成回复
const regenerateResponse = async (message: Message) => {
  // 找到对应的用户原始输入
  const messageIndex = messages.value.findIndex((m) => m.id === message.id);
  if (messageIndex === -1) return;

  let userInput = "";
  for (let i = messageIndex - 1; i >= 0; i--) {
    if (messages.value[i].type === "user") {
      userInput = messages.value[i].content;
      break;
    }
  }
  if (!userInput) return;

  // 显示"重新生成中"状态
  const loadingMessage = {
    ...message,
    content: "正在重新生成回复...",
    showActions: false,
    products: undefined,
    followUpQuestions: undefined,
  };
  messages.value[messageIndex] = loadingMessage;

  try {
    // 重新调用接口生成回复
    const newResponse = await generateBotResponse(userInput);
    messages.value[messageIndex] = {
      ...newResponse,
      id: message.id, // 保持原有ID
    };
  } catch (error) {
    messages.value[messageIndex] = {
      ...message,
      content: "重新生成失败，请稍后再试~",
    };
  }
};

// -------------------------- 滚动相关 --------------------------
// 商品列表滚动
const scrollProducts = (direction: "prev" | "next") => {
  if (!productGrid.value) return;

  const scrollAmount = 200;
  const currentScroll = productGrid.value.scrollLeft;

  if (direction === "prev") {
    productGrid.value.scrollLeft = currentScroll - scrollAmount;
  } else {
    productGrid.value.scrollLeft = currentScroll + scrollAmount;
  }

  // 更新滚动按钮可见性
  setTimeout(() => {
    updateScrollButtons();
  }, 100);
};

// 更新滚动按钮状态
const updateScrollButtons = () => {
  if (!productGrid.value) return;

  canScrollLeft.value = productGrid.value.scrollLeft > 0;
  canScrollRight.value =
    productGrid.value.scrollLeft <
    productGrid.value.scrollWidth - productGrid.value.clientWidth - 10;
};

// 监听商品列表滚动事件
const setupProductGridScroll = () => {
  nextTick(() => {
    if (productGrid.value) {
      productGrid.value.addEventListener("scroll", updateScrollButtons);
      updateScrollButtons(); // 初始化状态
    }
  });
};

// 滚动到最新消息
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    }
  });
};

// -------------------------- 默认问题相关 --------------------------
// 随机抽取数组中的指定数量元素
const getRandomItems = (
  array: DefaultQuestion[],
  count: number
): DefaultQuestion[] => {
  if (array.length <= count) {
    return [...array];
  }

  const shuffled = [...array];
  for (let i = shuffled.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
  }

  return shuffled.slice(0, count);
};

// 获取默认问题列表
const fetchDefaultQuestions = async () => {
  if (isLoadingQuestions.value) return;

  isLoadingQuestions.value = true;
  try {
    const response = await request(
      `${API_DEFAULT_QUESTIONS.baseUrl}${API_DEFAULT_QUESTIONS.endpoint}`
    );

    const apiData = response;
    if (apiData.code === "200" && apiData.data && Array.isArray(apiData.data)) {
      // 从返回的问题列表中随机抽取3条
      const allQuestions = apiData.data;
      defaultQuestions.value = getRandomItems(allQuestions, 3);
    } else {
      console.warn(
        "获取默认问题失败:",
        apiData.message || "接口返回数据格式错误"
      );
      // 使用备用问题
      defaultQuestions.value = [
        {
          questionsId: 1,
          questionContent: "ZKMALL-智客小助是什么?可以做什么?",
        },
        { questionsId: 2, questionContent: "怎么使用智客小助?" },
        {
          questionsId: 3,
          questionContent: "ZKMALL的商品怎么出现在智客小助里?",
        },
      ];
    }
  } catch (error) {
    console.error("获取默认问题失败:", error);
    // 使用备用问题
    defaultQuestions.value = [
      { questionsId: 1, questionContent: "ZKMALL-智客小助是什么?可以做什么?" },
      { questionsId: 2, questionContent: "怎么使用智客小助?" },
      { questionsId: 3, questionContent: "ZKMALL的商品怎么出现在智客小助里?" },
    ];
  } finally {
    isLoadingQuestions.value = false;
  }
};

// 刷新默认问题
const refreshDefaultQuestions = async () => {
  await fetchDefaultQuestions();
};

// -------------------------- 商品跳转相关 --------------------------
// 跳转到商品详情页面
const jumpToProductDetail = (product: Product) => {
  if (!product.shopId || !product.productId) {
    console.warn("商品信息不完整，无法跳转:", product);
    uni.showToast({
      title: "商品信息不完整",
      icon: "none",
    });
    return;
  }

  // 构建跳转URL，使用商品ID和SKU ID
  const productId = product.productId;
  const skuId = product.skuId || "";
  const shopId = product.shopId;

  const url = `/zwx_category_page1/goodsModule/goodsDetails?shopId=${shopId}&productId=${productId}&skuId=${skuId}`;
  console.log("跳转到商品详情:", { product });
  console.log("跳转到商品详情:", { shopId, productId, skuId, url });

  // 使用uni.navigateTo进行页面跳转
  uni.navigateTo({
    url: url,
    success: () => {
      console.log("成功跳转到商品详情页面");
    },
    fail: (error) => {
      console.error("页面跳转失败:", error);
      uni.showToast({
        title: "页面跳转失败",
        icon: "none",
        duration: 2000,
      });
    },
  });
};

// 初始化
setupProductGridScroll();
// 页面加载时获取默认问题
fetchDefaultQuestions();
</script>

<style lang="scss" scoped>
/* 重置样式，避免全局样式冲突 */
@import "../../style/images";
.chat-container {
  width: 100%;
  height: 100vh;
  background: #f5f5f5 url("#{$base-path}ui-static/zwx-static/ai/bg.png")
    no-repeat top center;
  display: flex;
  flex-direction: column;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
    "Helvetica Neue", Arial, sans-serif;
  position: relative;
  overflow: hidden;
}
.ai-intro-section {
  padding-top: 84rpx;
  position: relative;
  margin-bottom: 24rpx;
  .ai-top {
    background: url("#{$base-path}ui-static/zwx-static/ai/bg-top.png") no-repeat
      center / 100% auto;
    .ai-img {
      position: absolute;
      top: 0;
      left: 16rpx;
      width: 184rpx;
      height: 178rpx;
      background: url("#{$base-path}ui-static/zwx-static/ai/img.png") no-repeat
        center / 100% 100%;
    }
    .ai-greeting {
      margin-left: 232rpx;
      font-family: Alimama ShuHeiTi, Alimama ShuHeiTi;
      font-weight: bold;
      font-size: 40rpx;
      line-height: 56rpx;
      padding: 30rpx 0 54rpx;
      color: #ffffff;
    }
  }
  .ai-description {
    margin-top: -28rpx;
    background: linear-gradient(#ffdec8 0%, #ffffff 100%);
    border-radius: 32rpx;
    //border: 2rpx solid;
    //border-image: linear-gradient(
    //    180deg,
    //    rgba(255, 255, 255, 1),
    //    rgba(255, 255, 255, 0)
    //  )
    //  2 2;
    padding: 24rpx;
    font-size: 28rpx;
    color: #3b3b3b;
    line-height: 42rpx;
  }
}

.back-btn {
  background: transparent;
  border: none;
  color: #333333;
  padding: 8px;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 40px;
  min-height: 40px;
  transition: background-color 0.2s ease;
}

.back-btn:hover {
  background: #f0f0f0;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #333333;
  flex: 1;
  text-align: center;
  line-height: 1.2;
}

.header-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.action-btn {
  background: transparent;
  border: none;
  color: #666666;
  padding: 8px;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 36px;
  min-height: 36px;
  transition: background-color 0.2s ease;
}

.action-btn:hover {
  background: #f0f0f0;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 24rpx;
  -webkit-overflow-scrolling: touch;
  scroll-behavior: smooth;
}

.suggested-questions {
  margin-bottom: 24rpx;
  background-color: #ffffff;
  padding: 24rpx 24rpx 8rpx 24rpx;
  border-radius: 16rpx;
  border: 2rpx solid;
  border-image: linear-gradient(180deg, rgba(255, 255, 255, 1), rgba(255, 255, 255, 0)) 2 2;
  .questions-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24rpx;
    .title {
	  width: 124rpx;
      height: 30rpx;
      background: url("#{$base-path}ui-static/zwx-static/ai/title.png") no-repeat
        center / 100% 100%;
    }
    .refresh-btn {
      background: none;
      border: none;
      color: #ff6b35;
      font-size: 14px;
      cursor: pointer;
      display: flex;
      align-items: center;
      padding: 4px 8px;
      border-radius: 12px;
	  margin: 0;
	  .svg{
		width: 28rpx;
		height: 28rpx;
		margin-right: 8rpx;
	  }
	  &:after{
		display: none;
	  }
      &:hover {
        background: #fff3e0;
      }
      &:disabled {
        opacity: 0.6;
        cursor: not-allowed;
      }
      &:disabled:hover {
        background: none;
      }
    }
  }
}

/* 旋转动画 */
.rotating {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

.question-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.question-item {
  background: #F5F5F5;
  border-radius: 20rpx;
  padding: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  transition: all 0.2s ease;
  box-shadow: 0 2rpx 8px rgba(0, 0, 0, 0.08);
  font-size: 28rpx;
  color: #3B3B3B;
  line-height: 38rpx;
  margin-bottom: 24rpx;
  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
  }
  span {
    color: #333333;
    font-size: 14px;
    flex: 1;
    line-height: 1.4;
    word-break: break-word;
  }
  svg {
    color: #999999;
    flex-shrink: 0;
    margin-left: 8px;
  }
}

/* 加载状态样式 */
.loading-questions {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.question-skeleton {
  background: #ffffff;
  border-radius: 12px;
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  min-height: 56px;
}

.skeleton-text {
  height: 16px;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: loading 1.5s infinite;
  border-radius: 4px;
  flex: 1;
  margin-right: 8px;
}

.skeleton-icon {
  width: 16px;
  height: 16px;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: loading 1.5s infinite;
  border-radius: 2px;
  flex-shrink: 0;
}

@keyframes loading {
  0% {
    background-position: 200% 0;
  }

  100% {
    background-position: -200% 0;
  }
}

/* 无问题时的占位样式 */
.no-questions {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 32px 16px;
  text-align: center;
  color: #999999;
  font-size: 14px;
  border: 1px dashed #e0e0e0;
}

.message-group {
  margin-bottom: 16px;
}

.user-message {
  display: flex;
  justify-content: flex-end;
}

.bot-message {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.message-bubble {
  max-width: 100%;
  padding: 18rpx 24rpx;
  border-radius: 20rpx;
  font-size: 28rpx;
  line-height: 42rpx;
  word-wrap: break-word;
  word-break: break-word;
}

.user-bubble {
  background: #ff6b35;
  color: #ffffff;
  border-bottom-right-radius: 6px;
}

.bot-bubble {
  background: #FFEEE6;
  color: #333333;
  border-bottom-left-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #f0f0f0;
}

.markdown-content {
  width: 100%;
}

.intro-block {
  background: linear-gradient(135deg, #fff3e0 0%, #ffe0b2 100%);
  border: 1px solid #ffcc80;
  border-radius: 8px;
  padding: 12px 16px;
  margin-bottom: 12px;
  color: #e65100;
  font-size: 14px;
  line-height: 1.5;
  position: relative;
}

.intro-block::before {
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  background: #ff6b35;
  border-radius: 2px;
}

.code-block {
  background: #f5f5f5;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  padding: 12px;
  margin: 8px 0;
  overflow-x: auto;
  font-family: "Courier New", monospace;
  font-size: 13px;
  line-height: 1.4;
}

.inline-code {
  background: #f0f0f0;
  border: 1px solid #ddd;
  border-radius: 3px;
  padding: 2px 4px;
  font-family: "Courier New", monospace;
  font-size: 12px;
  color: #d32f2f;
}

.md-heading {
  margin: 12px 0 8px 0;
  color: #2d3436;
  font-weight: 600;
}

.md-heading.h1 {
  font-size: 18px;
}

.md-heading.h2 {
  font-size: 16px;
}

.md-heading.h3 {
  font-size: 15px;
}

.md-list {
  margin: 8px 0;
  padding-left: 24px;
}

.md-list-item {
  margin: 4px 0;
  line-height: 1.5;
}

.md-image {
  max-width: 100%;
  border-radius: 8px;
  margin: 8px 0;
  display: block;
}

.message-actions {
  display: flex;
  gap: 8px;
  margin-top: 8px;
}

.product-recommendations {
  margin-top: 16px;
  width: 100%;
}

.product-carousel {
  position: relative;
  display: flex;
  align-items: center;
}

.carousel-btn {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background: white;
  border: 1px solid #ddd;
  border-radius: 50%;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 10;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.prev-btn {
  left: -18px;
}

.next-btn {
  right: -18px;
}

.carousel-btn:hover {
  background: #f5f5f5;
}

.product-grid {
  display: flex;
  gap: 12rpx;
  overflow-x: auto;
  scroll-behavior: smooth;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.product-grid::-webkit-scrollbar {
  display: none;
}

.product-card {
  background: #ffffff;
  border-radius: 8rpx;
  overflow: hidden;
  width: 200rpx;
  padding: 4rpx;
  transition: all 0.2s ease;
  position: relative;
  flex-shrink: 0;
}

.product-card:hover {
  border-color: #ff6b35;
}

.product-image {
  position: relative;
  overflow: hidden;
  .product-img {
    width: 186rpx;
    height: 186rpx;
    object-fit: cover;
  }
}

.product-badge {
  position: absolute;
  top: 6px;
  left: 6px;
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 10px;
  font-weight: bold;
}

.product-badge.hot {
  background: #ff4757;
}

.product-badge.recommended {
  background: #2ed573;
}

.product-info {
  padding: 0px;
}

.product-name {
  font-size: 24rpx;
  line-height: 1.5;
  margin: 0 0 10rpx 0;
  color: #333333;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  height: 64rpx;
  word-break: break-word;
}

.product-price {
  display: flex;
  align-items: baseline;
  gap: 6px;
  margin-bottom: 8px;
  flex-wrap: wrap;
}

.sale-price {
  font-size: 24rpx;
  color: #F53F3F;
}

.original-price {
  color: #999999;
  font-size: 12px;
  text-decoration: line-through;
}

.price-unit {
  color: #666666;
  font-size: 12px;
}

.contact-btn {
  width: 160rpx;
  background: #FF5000;
  border-radius: 24rpx;
  font-size: 24rpx;
  color: #FDFDFD;
  line-height: 48rpx;
  margin: 0 auto;
}

.contact-btn:active {
  transform: scale(0.98);
  background: #e55a2b;
}

.contact-btn:hover {
  background: #e55a2b;
}

.follow-up-questions {
  margin-top: 12px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.follow-up-item {
  background: #ffffff;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 8px 12px;
  font-size: 13px;
  color: #495057;
  cursor: pointer;
  transition: background-color 0.2s;
}

.follow-up-item:hover {
  background: #e9ecef;
}

.regenerate-section {
  margin-top: 24rpx;
}

.regenerate-btn {
  background: #FFFFFF;
  box-shadow: 0px 8rpx 16rpx 0px rgba(0,0,0,0.1);
  border-radius: 64rpx;
  color: #3B3B3B;
  padding: 12rpx 24rpx;
  font-size: 28rpx;
  line-height: 44rpx;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.regenerate-btn:hover {
  background: #fff3e0;
}

.chat-input {
  margin: 0 24rpx var(--window-bottom);
  padding-bottom: 20rpx;
  .input-container {
    display: flex;
    gap: 16rpx;
    align-items: center;
    background: #FFFFFF;
    border-radius: 20rpx;
    padding: 8rpx 10rpx 8rpx 24rpx;
    .message-input {
      flex: 1;

      &:focus {
        border-color: #ff6b35;
        background: white;
      }
    }
    .send-btn {
      margin: 0;
      background: linear-gradient( 90deg, #FF9000 0%, #FF5000 99%, #FF5000 100%);
      border-radius: 20rpx;
      font-size: 28rpx;
      color: #FFFFFF;
      line-height: 36rpx;
      padding: 14rpx 32rpx;
    }
  }

}

/* 修复滚动问题 */
.product-grid {
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.product-grid::-webkit-scrollbar {
  display: none;
}

/* 修复flex布局问题 */
.product-carousel {
  width: 100%;
}

.carousel-btn {
  z-index: 10;
}

/* 修复文字显示问题 */

/* 确保图片响应式 */


/* 确保滚动流畅 */
.chat-messages {
  scroll-behavior: smooth;
}

.product-grid {
  scroll-behavior: smooth;
}
</style>
